from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from celery_tasks.send_email.tasks import send_email_task
from django.contrib.auth.models import User
from django_redis import get_redis_connection
from django.conf import settings


class EmailView(APIView):
    ''' 发送邮箱验证码 '''
    def get(self, request, email, sig):
        redis_conn = get_redis_connection('verfication')
        # 判断是否频繁发送验证码
        if redis_conn.get('email_%s_flag' % email):
            return Response({'messages': '请求频繁，请稍后再试。'}, status=status.HTTP_400_BAD_REQUEST)
        # 判断邮箱是否已注册
        if User.objects.filter(email=email).exists():
            return Response({'messages': '该邮箱已注册。'}, status=status.HTTP_400_BAD_REQUEST)
        # 发送验证码
        send_email_task.delay(email, sig)
        return Response({'messages': '发送成功'})


class EmailActiveView(APIView):
    ''' 邮箱激活认证 '''
    def get(self, request, email, code):
        redis_conn = get_redis_connection('verfication')
        # 判断邮箱验证码是否正确
        code_ = redis_conn.get('email_%s' % email)
        if not code_ or code_.decode() != code:
            error = {'result': 'error', 'msg': '激活失败'}
            return render(request, 'email_active.html', context=error)
        # 验证成功，新增 已激活 缓存
        redis_conn.setex('email_%s_active' % email, settings.EMAIL_ACTIVE_EX, 1)
        success = {'result': 'success', 'msg': '激活成功'}
        return render(request, 'email_active.html', context=success)
